package com.cloud.demo2020.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cloud.demo2020.common.ResultBean;
import com.cloud.demo2020.entity.SysToken;
import com.cloud.demo2020.entity.SysUserDto;
import com.cloud.demo2020.mapper.SysTokenMapper;
import com.cloud.demo2020.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

@Service
public class UserService {
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysTokenMapper sysTokenMapper;

    @Autowired
    private CodeService codeService;

    @Transactional
    public ResultBean register(SysUserDto user) {
        ResultBean r = this.codeService.valid(user.getEmail(), user.getCode());
        int data = (int) r.getData();
        if (data !=0) {
            return new ResultBean(false, "请输入正确的验证码");
        }

        this.sysUserMapper.insert(user);
        SysToken token = new SysToken();
        token.setEmail(user.getEmail());
        token.setToken(UUID.randomUUID().toString());
        token.setUpdatetime(new Date());
        this.sysTokenMapper.delete(
                new UpdateWrapper<SysToken>().eq("email", user.getEmail()));
        this.sysTokenMapper.insert(token);

        return new ResultBean(token);
    }
}
